package com.solareast.controller.app.visitor;

import java.util.*;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.solareast.util.dingtalk.AppConstant;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.solareast.controller.base.BaseController;
import com.solareast.util.PageData;
import com.solareast.service.app.visitor.VisitorService;
import com.solareast.util.*;
import com.solareast.util.dingtalk.AccessTokenUtil;
import com.solareast.util.dingtalk.UserUtil;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiWorkrecordAddRequest;
import com.dingtalk.api.response.OapiWorkrecordAddResponse;
import com.dingtalk.api.request.OapiUserGetByMobileRequest;
import com.dingtalk.api.response.OapiUserGetByMobileResponse;
import com.taobao.api.internal.util.StringUtils;



/** 
 * 类名称：VisitorController
 * 创建人：solareast 
 * 创建时间：2021-09-01
 */
@Controller
@RequestMapping(value="/visitor")
public class VisitorController extends BaseController {

	String menuUrl = "visitor/list.do"; //菜单地址(权限用)
	String appName = AppConstant.H5TEST_NAME;

	@Resource(name = "VisitorService")
	private VisitorService VisitorService;




	/**
	 * 列表
	 */
//	@RequestMapping(value="/list")
//	public ModelAndView list(Page page){
//		logBefore(logger, "列表VisitorController");
//		//if(!Jurisdiction.buttonJurisdiction(menuUrl, "cha")){return null;} //校验权限
//		ModelAndView mv = this.getModelAndView();
//		PageData pd = new PageData();
//		try{
//			pd = this.getPageData();
//			page.setPd(pd);
//			List<PageData>	varList = VisitorService.list(pd);	//列出VisitorController列表
//			mv.setViewName("app/visitor/visitor_list");
//			mv.addObject("varList", varList);
//			mv.addObject("pd", pd);
//			logger.info(pd);
//			logger.info(varList);
////			mv.addObject(Const.SESSION_QX,this.getHC());	//按钮权限
//		} catch(Exception e){
//			logger.error(e.toString(), e);
//		}
//		return mv;
//	}
	/**
	 * 列表
	 */
	@RequestMapping(value = "/list")
	public ModelAndView list() throws Exception{
		ModelAndView mv = this.getModelAndView();
		mv.setViewName("app/visitor/visitor_list");
		return mv;
	}

	@RequestMapping(value = "/visitorlist")
	@ResponseBody
	public JSONObject visitorlist(int page,int limit) throws Exception{
		PageData pd = this.getPageData();
		pd.put("page",(page-1)*limit);
		pd.put("limit",limit);
		List<PageData> listRate = VisitorService.list(pd);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("code", 0);
		result.put("msg", "");
		PageData visitorcount = VisitorService.listCount(pd);
		result.put("count", visitorcount.get("listcount"));
		result.put("data", listRate);
		return JSONObject.parseObject(JSON.toJSONString(result));
	}

	/**
	 *
	 * @param sname
	 * @param stel
	 * @param vtime
	 * @param incheck
	 * @param page
	 * @param limit
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/searchlist")
	@ResponseBody
	public JSONObject searchlist(String sname,String stel,String vtime,String incheck, int page,int limit) throws Exception{
		PageData pd = this.getPageData();
		pd.put("sname",sname);
		pd.put("vtime",vtime);
		pd.put("stel",stel);
		pd.put("incheck",incheck);
		pd.put("page",(page-1)*limit);
		pd.put("limit",limit);
		List<PageData> listRate = VisitorService.list(pd);
		PageData visitorcount = VisitorService.listCount(pd);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("code", 0);
		result.put("msg", "");
		result.put("count", visitorcount.get("listcount"));
		result.put("data", listRate);
		return JSONObject.parseObject(JSON.toJSONString(result));
	}



	/**
	 * 去新增页面
	 */
	@RequestMapping(value = "/goAdd")
	public ModelAndView goAdd() {
		//logBefore(logger, "去新增VisitorController页面");
		ModelAndView mv = this.getModelAndView();
		PageData pd = new PageData();
		pd = this.getPageData();
		try {
			mv.setViewName("app/visitor/visitor_add");
			mv.addObject("pd", pd);
		} catch (Exception e) {
			logger.error(e.toString(), e);
		}
		return mv;
	}

	/**
	 *
	 * @param date
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/savevisitor")
	@ResponseBody
	public JSONObject savevisitor(@RequestBody String date) throws Exception {
		JSONObject field = JSONObject.parseObject(date).getJSONObject("field");
		PageData pd = new PageData();
		String id = UuidUtil.get32UUID();
		String incheck = "未确认";
		pd.put("id", id);
		if(field.getString("vname")!=null){
			pd.put("vname",field.getString("vname"));}
		else {
			pd.put("vname","");
		}
		pd.put("vdept", field.getString("vdept"));
		pd.put("sname", field.getString("sname"));
		pd.put("sdept", field.getString("sdept"));
		pd.put("stel", field.getString("stel"));
		//pd.put("userid", field.getString("userid"));
		pd.put("vtext", field.getString("vtext"));
		pd.put("vtime", field.getString("vtime"));
		pd.put("incheck", incheck);
		//通过手机号获取用户工号

		String accessToken = AccessTokenUtil.getToken(appName);

		DingTalkClient client1 = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get_by_mobile");
		OapiUserGetByMobileRequest req1 = new OapiUserGetByMobileRequest();
		req1.setMobile(field.getString("stel")); //stel
		req1.setHttpMethod("GET");
		OapiUserGetByMobileResponse rsp1 = client1.execute(req1, accessToken);
		System.out.println(rsp1.getBody());//pd.put("record_id",rsp.getRecordId());
		//pd.put("userid",rsp1.getUserid());
			//	logger.info("rsp1="+rsp1.getUserid());





	//发送代办任务
		//String accessToken = AccessTokenUtil.getToken(appName);
		DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/workrecord/add");
		// 调用钉钉接口发起代办任务

		     //   logger.info("incheck="+ incheck);

		OapiWorkrecordAddRequest req = new OapiWorkrecordAddRequest();
		req.setUserid(rsp1.getUserid());

		req.setCreateTime(System.currentTimeMillis());
		req.setTitle("访客信息");
		 req.setUrl("http://dingtalk.solareast.com/solareast-dingtalk/visitor/check.do?id="+id);
		//req.setUrl("http://xting.vaiwan.com/solareast-dingtalk/visitor/check.do?id=" + id);
		List<OapiWorkrecordAddRequest.FormItemVo> list2 = new ArrayList<OapiWorkrecordAddRequest.FormItemVo>();
		OapiWorkrecordAddRequest.FormItemVo obj3 = new OapiWorkrecordAddRequest.FormItemVo();
		OapiWorkrecordAddRequest.FormItemVo obj4 = new OapiWorkrecordAddRequest.FormItemVo();

		obj4.setTitle("访客姓名");
		obj4.setContent(field.getString("vname"));
		list2.add(obj4);
		obj3.setTitle("来访事由");
		obj3.setContent(field.getString("vtext"));
		list2.add(obj3);
		req.setFormItemList(list2);
		OapiWorkrecordAddResponse rsp = client.execute(req, accessToken);

//		logger.info("userid="+ userid );
		Map<String, Object> result = new HashMap<String, Object>();
		if(rsp.getErrcode()==0L){
			pd.put("record_id",rsp.getRecordId());
			VisitorService.save(pd);
			result.put("code", 0);
			result.put("msg", "登记成功，请稍等片刻。");
		}else{
			pd.put("record_id","");
			VisitorService.save(pd);
			result.put("code", 1);
			result.put("msg", rsp.getErrmsg());
		}
		return JSONObject.parseObject(JSON.toJSONString(result));
	}
	/**
	 *
	 * @return
	 */
	@RequestMapping(value = "/getauth")
	public ModelAndView getAuthCode(String id){
		ModelAndView mv = this.getModelAndView();
		mv.addObject("id",id);
		mv.setViewName("app/visitor/visitor_get_auth");
		return mv;
	}

	/**
	 * 获取用户免登信息
	 *
	 * @param authCode
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/indexlogin")
	@ResponseBody
	public String indexLogin(String authCode) throws Exception {
		if (StringUtils.isEmpty(authCode)) {
			logger.error("未获取到authCode参数!");
			return null;
		}
		String str_msg = null;

		String accessToken = AccessTokenUtil.getToken(appName);

		String userId = UserUtil.getUserId(accessToken, authCode);

		if (userId.isEmpty()) {
			return "error,userId is empty";
		}

		str_msg = "success";
		return str_msg;
	}

	/**
	 *
	 * @return
	 *
	 */
	@RequestMapping(value = "/check")
	public ModelAndView check(HttpServletRequest request) throws Exception {
		ModelAndView mv = this.getModelAndView();
		StringBuffer msg = new StringBuffer();
		String id = request.getParameter("id");
		PageData pd = new PageData();
		pd.put("id", id);
		try{
//			logger.info("id="+ field.getString("id"));
//			logger.info(id);
			//获取用户信息
			pd = VisitorService.findById(pd);
			msg.append("获取用户信息成功！");
		}catch(Exception e){
			msg.append("获取用户信息时发生错误！");
			throw e;
		}
		mv.addObject("msg",msg);
		mv.addObject("pd",pd);
		mv.setViewName("app/visitor/visitor_check");

		// logger.info("pd="+pd);

		return mv;
	}

	/**
	 *
	 * @param date
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/inchecksave")
	@ResponseBody
	public JSONObject inchecksave(@RequestBody String date,	String id ) throws Exception{
		JSONObject field = JSONObject.parseObject(date).getJSONObject("field");
		PageData pd = new PageData();
		pd.put("id", id);
		VisitorService.insert(pd);
        logger.info(id);
		Map<String, Object> result = new HashMap<String, Object>();
		result.put("code", 0);
		result.put("msg", "祝您会客愉快！");
		return JSONObject.parseObject(JSON.toJSONString(result));
	}


//	/* ===============================权限================================== */
//	public Map<String, String> getHC(){
//		Subject currentUser = SecurityUtils.getSubject();  //shiro管理的session
//		Session session = currentUser.getSession();
//		return (Map<String, String>)session.getAttribute(Const.SESSION_QX);
//	}
//	/* ===============================权限================================== */
//
//	@InitBinder
//	public void initBinder(WebDataBinder binder){
//		DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
//		binder.registerCustomEditor(Date.class, new CustomDateEditor(format,true));
//	}


}
